<?php
namespace Demo\App\Handler;

use Swork\Bean\ScanHandlerInterface;
use Swork\Command;

class ScanHandler implements ScanHandlerInterface
{
    public function afterAnalyzeMethod(\ReflectionClass $rc, \ReflectionMethod $method, string $route)
    {
        //解析函数内容
        $fileName = $rc->getFileName();
        $methodName = $method->getName();
        $content = file_get_contents($fileName);
        preg_match("/function\s+{$methodName}([\S\s]*?)API返回([\s\S]+)return/", $content, $matches);
        if (count($matches) < 2)
        {
            return;
        }

        //解析参数
        $arguments = $this->parseArguments($matches[1]);
//        $rst =  json_encode($arguments, JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE);
//        file_put_contents('xxx.json', $rst);

        //解析返回
        $rst = '';
        if (!empty($matches[2]))
        {
            $rst = $this->parseReturn($matches[2]);
        }


    }

    /**
     * 解析参数
     * @param string $content
     * @return array
     */
    private function parseArguments(string $content)
    {
        preg_match_all('/\/\*+[\s\S]*?->(get|post|query)\([\'\"](\w+)/', $content, $matches);
        $arguments = [];
        foreach ($matches[0] as $key => $item)
        {
            //参数名
            $name = $matches[2][$key] ?? '';
            if (empty($name))
            {
                continue;
            }

            //参数注解解析
            preg_match('/\/\*+([\s\S]*?)@/', $item, $descMatches);
            $desc = $descMatches[1] ?? '';
            $desc = str_replace('*', '', $desc);
            $desc = trim($desc);
            preg_match('/@var(.*)/', $item, $typeMatches);
            $type = trim($typeMatches[1] ?? '');
            preg_match('/@require(.*)/', $item, $requireMatches);
            $require = count($requireMatches) >= 2;
            preg_match('/@sample(.*)/', $item, $sampleMatches);
            $sample = trim($sampleMatches[1] ?? '');

            //追加数组
            $arguments[] = [
                'name' => $name,
                'desc' => $desc,
                'type' => $type,
                'require' => $require,
                'sample' => $sample,
            ];
        }

        //返回
        return $arguments;
    }

    /**
     * 解析返回
     * @param string $content
     * @return string
     */
    private function parseReturn(string $content)
    {
        preg_match('/\/\*+([\s\S]*?)\*\//', $content, $matches);

        //返回
        return $matches[1] ?? '';
    }
}
